import React, { useState, useEffect } from 'react';
import type { VoiceCharacter, VoiceSettings } from '../types/voiceSettings';
import { DEFAULT_VOICE_SETTINGS } from '../types/voiceSettings';
import { voiceChatManager } from '../services/voiceChatManager';
import './VoiceSettings.css';

interface VoiceSettingsPanelProps {
    onClose: () => void;
}

const VoiceSettingsPanel: React.FC<VoiceSettingsPanelProps> = ({ onClose }) => {
    const [voiceSettings, setVoiceSettings] = useState<VoiceSettings>(DEFAULT_VOICE_SETTINGS);
    const [selectedCharacter, setSelectedCharacter] = useState<string>('xiaoyan');

    // 从本地存储加载设置
    useEffect(() => {
        const savedSettings = localStorage.getItem('voiceSettings');
        if (savedSettings) {
            try {
                const parsed = JSON.parse(savedSettings);
                // 合并设置，但总是使用最新的角色定义
                const mergedSettings = {
                    ...parsed,
                    characters: DEFAULT_VOICE_SETTINGS.characters // 总是使用最新的角色数据
                };
                setVoiceSettings(mergedSettings);
                const currentCharacter = parsed.currentCharacter || 'xiaoyan';
                setSelectedCharacter(currentCharacter);

                // 重要：加载设置后立即更新voiceChatManager的TTS参数
                voiceChatManager.setVoiceCharacter(currentCharacter);
            } catch (error) {
                console.error('Failed to parse voice settings:', error);
            }
        } else {
            // 如果没有保存的设置，使用默认设置
            setVoiceSettings(DEFAULT_VOICE_SETTINGS);
            setSelectedCharacter('xiaoyan');
            // 重要：设置默认语音
            voiceChatManager.setVoiceCharacter('xiaoyan');
        }
    }, []);

    // 保存设置到本地存储
    const saveSettings = (newSettings: VoiceSettings) => {
        localStorage.setItem('voiceSettings', JSON.stringify(newSettings));
        setVoiceSettings(newSettings);
    };

    // 处理语音角色选择
    const handleCharacterSelect = (characterId: string) => {
        const character = voiceSettings.characters.find(c => c.id === characterId);
        if (character) {
            setSelectedCharacter(characterId);

            // 使用setVoiceCharacter方法，这会正确设置所有参数
            voiceChatManager.setVoiceCharacter(characterId);

            // 保存设置
            const newSettings = {
                ...voiceSettings,
                currentCharacter: characterId
            };
            saveSettings(newSettings);

            console.log('🎤 语音角色已切换为:', character.name, character.description);
        }
    };

    // 测试语音
    const testVoice = async (character: VoiceCharacter) => {
        const testText = '你好，我是' + character.name + '，这是我的声音效果。';

        // 临时设置TTS参数
        voiceChatManager.setTtsParams({
            vcn: character.vcn,
            speed: character.speed,
            volume: character.volume,
            pitch: character.pitch
        });

        // 播放测试语音
        voiceChatManager.stopSpeaking(); // 先停止当前播放
        setTimeout(async () => {
            try {
                await voiceChatManager.testVoice(testText);
            } catch (error) {
                console.error('语音测试失败:', error);
            }
        }, 100);
    };

    // 按分类分组
    const groupedCharacters = voiceSettings.characters.reduce((acc, character) => {
        if (!acc[character.category]) {
            acc[character.category] = [];
        }
        acc[character.category].push(character);
        return acc;
    }, {} as Record<string, VoiceCharacter[]>);

    const categoryNames = {
        female: '女性声音',
        male: '男性声音',
        child: '儿童声音',
        special: '特殊声音',
        dialect: '方言语种'
    };

    return (
        <div className="voice-settings-overlay">
            <div className="voice-settings-panel">
                <div className="voice-settings-header">
                    <h3>🎤 语音设置</h3>
                    <button className="voice-settings-close" onClick={onClose}>
                        ×
                    </button>
                </div>

                <div className="voice-settings-content">
                    <div className="voice-settings-section">
                        <h4>当前语音角色</h4>
                        <div className="current-voice">
                            {voiceSettings.characters.find(c => c.id === selectedCharacter)?.name || '小燕'}
                            <span className="voice-description">
                                {voiceSettings.characters.find(c => c.id === selectedCharacter)?.description || '温柔女声'}
                            </span>
                        </div>
                    </div>

                    <div className="voice-settings-section">
                        <h4>选择语音角色</h4>
                        {Object.entries(groupedCharacters).map(([category, characters]) => (
                            <div key={category} className="voice-category">
                                <h5>{categoryNames[category as keyof typeof categoryNames]}</h5>
                                <div className="voice-characters-grid">
                                    {characters.map(character => (
                                        <div
                                            key={character.id}
                                            className={`voice-character-card ${selectedCharacter === character.id ? 'selected' : ''}`}
                                            onClick={() => handleCharacterSelect(character.id)}
                                        >
                                            <div className="voice-character-name">{character.name}</div>
                                            <div className="voice-character-description">{character.description}</div>
                                            <div className="voice-character-params">
                                                <span>语速: {character.speed}</span>
                                                <span>音量: {character.volume}</span>
                                                <span>音调: {character.pitch}</span>
                                            </div>
                                            <button
                                                className="voice-test-btn"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    testVoice(character);
                                                }}
                                            >
                                                🔊 试听
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))}
                    </div>

                    <div className="voice-settings-footer">
                        <button className="voice-settings-save" onClick={onClose}>
                            完成
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default VoiceSettingsPanel;
